package com.ks.service;

import com.ks.base.BaseService;
import com.ks.dao.*;
import com.ks.entity.*;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("examService")
@Transactional
public class ExamService<T> extends BaseService<T> {
    private final static Logger log = Logger.getLogger(ExamService.class);

    @Autowired
    private ExamDao<T> dao;
    @Autowired
    private ExamPaperDao<T> examPaperDao;
    @Autowired
    private ExamDao<T> examDao;
    @Autowired
    private PaperDao<T> paperDao;
    @Autowired
    private PaperQuestionDao<T> paperQuestionDao;
    @Autowired
    private UnitDao<T> unitDao;
    @Autowired
    private UserDao<T> userDao;
    @Autowired
    private ExamParenttypeDao<T> examParenttypeDao;
    @Autowired
    private ProfessionDao<T> professionDao;
    @Autowired
    private RankDao<T> rankDao;
    @Autowired
    private ExamineeDao<T> examineeDao;
    @Autowired
    private DepositoryDao<T> despositoryDao;
    @Autowired
    private ContentDao<T> contentDao;
    @Autowired
    private QuestionDao<T> questionDao;
    @Autowired
    private QuestionCopyDao<T> questionCopyDao;

    public ExamDao<T> getDao() {
        return dao;
    }

    /**
     *
     * @param name
     * @param starttime
     * @param duration
     * @param questionrandom
     * @param optionrandom
     * @param address
     * @param creater
     * @param unit
     * @param type
     * @param pro
     * @param rank
     * @return
     */
    public Map<String, Object> addExamFirstStep(String examId,String name, String starttime, String duration, String questionrandom,
                                                String optionrandom, String address, Integer creater, Integer unit,
                                                String type, String pro, String rank) {
        Map<String, Object> resultMap = new HashMap<>();
        Integer status = 1;
        String msg = "";

        ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
        Exam exam = (Exam) ac.getBean("exam");
        exam.setName(name);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = sdf.parse(starttime);
            exam.setStarttime(date);
        } catch (ParseException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }

        exam.setDuration(duration);
        exam.setQuestionrandom(questionrandom);
        exam.setOptionrandom(optionrandom);
        exam.setAddress(address);
        exam.setCreater(creater);
        exam.setUnit(unit);
        exam.setType_id(Integer.parseInt(type));
        exam.setPro_id(Integer.parseInt(pro));
        exam.setRank_id(Integer.parseInt(rank));
        if (StringUtils.isNotBlank(examId)) {
            exam.setId(Integer.parseInt(examId));
            dao.update(exam);
        } else {
            dao.add(exam);
        }
        resultMap.put("examId", exam.getId());
        resultMap.put("status", status);
        resultMap.put("msg", msg);
        return resultMap;
    }
    public Map<String, Object> toAddExam(User user) {
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("userInfo", user);
        Unit unit = (Unit) unitDao.queryById(user.getUnit_id());
        resultMap.put("unit", unit);
        // 查询考试大类
        List<ExamParenttype> typeList = (List<ExamParenttype>) examParenttypeDao.queryList(null);
        if (!typeList.isEmpty()) {
            resultMap.put("typeList", typeList);
        }
        // 查询专业
        List<Profession> proList = (List<Profession>) professionDao.queryList(null);
        if (!proList.isEmpty()) {
            resultMap.put("proList", proList);
        }
        //查询所有部门
        List<Unit> units = (List<Unit>) unitDao.queryList(null);
        List<JSONObject> jsons = this.getJson(units);
        resultMap.put("units", jsons);
        return  resultMap;
    }

    public List<Map<String, Object>> paperList(Exam exam) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("status", 1);
        List<Paper> paperList = new ArrayList<>();
        if (null !=exam.getId()) {
            Exam examEntity = (Exam) dao.queryById(exam);
            //paramMap.put("type_id",examEntity.getType_id());
            paperList = paperDao.queryExamPapers(paramMap);
        }
        List<Map<String, Object>> resultMapList = new ArrayList<>();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Map<String, Object> dataMap;
        Map<String, Object> dataMap2;
        for (Paper paper : paperList) {
            dataMap = new HashMap<String, Object>();
            dataMap2 = new HashMap<String, Object>();
            dataMap.put("id", paper.getId());
            dataMap.put("title", paper.getTitle());
            dataMap.put("score", paper.getScore());
            dataMap.put("updatetime", sdf.format(paper.getUpdatetime()));
            // 创建人
            User createUser = (User) userDao.queryById(paper.getCreater());
            dataMap.put("creater", createUser.getName());
            // 题量
            dataMap2.put("paper_id", paper.getId());
            dataMap.put("questionCount", paperQuestionDao.queryListByPaperId(dataMap2));
            // 使用次数
            dataMap.put("useCount", examPaperDao.queryListByPaperId(dataMap2));
            resultMapList.add(dataMap);
        }
        return resultMapList;
    }

    public List<Map<String, Object>> examList() {
        // 考试基本信息
        List<Map<String, Object>> examList = new ArrayList<>();
        List<Exam> examInfoList = dao.findAllDesc(null);
        Map<String, Object> dataMap = null;
        if (!examInfoList.isEmpty()) {
            for (Exam exam : examInfoList) {
                dataMap = new HashMap<String, Object>();
                dataMap.put("examId", exam.getId());
                dataMap.put("examName", exam.getName());
                dataMap.put("publishCode", exam.getPublish());
                if ("1".equals(exam.getPublish())) {
                    dataMap.put("publish", "已发布");
                } else {
                    dataMap.put("publish", "未发布");
                }
                List<Examinee> examineeList = (List<Examinee>) examineeDao.queryByExamId(exam.getId());
                dataMap.put("studentCount", examineeList.size());
                dataMap.put("examStatus", exam.getStatus());
                examList.add(dataMap);
            }
        }
        return examList;
    }


    /**
     * 创建考试第二步
     *
     * @param paperId
     * @param examId
     * @return
     */
    public Map<String, Object> addExamSecondStep(String paperId, String examId) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> dataMap = new HashMap<>();
        Integer status = 1;
        String msg = "";
        ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
        ExamPaper examPaper = (ExamPaper) ac.getBean("examPaper");

        if (StringUtils.isNotBlank(paperId) && StringUtils.isNotBlank(examId)) {
            examPaper.setPaper_id(Integer.parseInt(paperId));
            examPaper.setExam_id(Integer.parseInt(examId));
            examPaperDao.add(examPaper);
            // 查询考试人员
            dataMap.put("exam_id", examId);
            List<User> userList = (List<User>) userDao.queryListByExam(dataMap);
            if (!userList.isEmpty()) {
                resultMap.put("userList", userList);
                msg = "操作成功！";
            } else {
                status = 0;
                msg = "系统异常！";
            }
        } else {
            status = 0;
            msg = "系统异常！";
        }
        resultMap.put("status", status);
        resultMap.put("msg", msg);
        return resultMap;

    }

    /**
     * 创建考试第三步
     *
     * @param studentIds
     * @param examId
     * @return
     */
    @Transactional
    public Map<String, Object> addExamThirdStep(String studentIds, String examId, String paperId) {

        ApplicationContext ac = null;
        Map<String, Object> resultMap = new HashMap<>();
        Integer status = 1;
        String msg = "操作成功！";
        List<String> studentNameList = new ArrayList<>();
        //删除考试中的考生
        examineeDao.deleteFromExamId(examId);
        if (StringUtils.isNotBlank(studentIds)) {
            String studentArry[] = studentIds.split(",");
            for (int i = 0; i < studentArry.length; i++) {
                ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
                Examinee examinee = (Examinee) ac.getBean("examinee");
                examinee.setExam_id(Integer.parseInt(examId));
                examinee.setUser_id(Integer.parseInt(studentArry[i]));
                examineeDao.add(examinee);
            }
        }

        // 获取考试信息
        Exam exam = (Exam) dao.queryById(examId);
        if (null != exam) {
            resultMap.put("name", exam.getName());
            if (StringUtils.isBlank(exam.getPublish()) || "0".equals(exam.getPublish())) {
                resultMap.put("publish", "未发布");
            } else {
                resultMap.put("publish", "已发布");
            }
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            // resultMap.put("starttime", sdf.format(exam.getStarttime()));
            resultMap.put("duration", exam.getDuration() + "分钟");
            // 考试人数
            List<Examinee> examineeList = (List<Examinee>) examineeDao.queryByExamId(examId);
            if (!examineeList.isEmpty()) {
                resultMap.put("renshu", "应到" + examineeList.size() + "人");
                // 组建考生姓名list
                for (Examinee exami : examineeList) {
                    User user = (User) userDao.queryById(exami.getUser_id());
                    String stuName = user.getName();
                    studentNameList.add(stuName);
                }
                resultMap.put("studentList", studentNameList);
            }
            resultMap.put("address", exam.getAddress());
        }
        // 获取试卷信息
        Paper paper = (Paper) paperDao.queryById(paperId);
        if (null != paper) {
            resultMap.put("paperName", paper.getTitle());
            // 查询题库
            Depository dep = (Depository) despositoryDao.queryById(paper.getDepository_id());
            // 查询章节
            Content con = (Content) contentDao.queryById(paper.getExtend());
            //题库和对应的知识点
            resultMap.put("depository", dep.getName() + "->" + con.getTitle());
            //试题预览
            // 题目数量
            resultMap.put("questionCount", paperQuestionDao.queryListByPaperId(paper.getId()));
            resultMap.put("score", paper.getScore());
        }

        resultMap.put("status", status);
        resultMap.put("msg", msg);

        return resultMap;

    }

    /**
     * 创建考试第四步
     *
     * @param examId
     * @return
     */
    public Map<String, Object> addExamFourthStep(String examId) {
        Map<String, Object> resultMap = new HashMap<>();
        String msg = "操作成功！";
        ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
        Exam exam = (Exam) ac.getBean("exam");
        if (StringUtils.isNotBlank(examId)) {
            exam.setId(Integer.parseInt(examId));
            exam.setPublish("1");
            dao.updateBySelective(exam);
        }
        resultMap.put("status", 1);
        resultMap.put("msg", msg);
        return resultMap;
    }

    public void toExamDetail(Model model, String examId) {
        List<String> studentNameList = new ArrayList<>();
        // 获取考试信息
        Exam exam = (Exam) dao.queryById(examId);
        if (null != exam) {
            model.addAttribute("name", exam.getName());
            if (StringUtils.isBlank(exam.getPublish()) || "0".equals(exam.getPublish())) {
                model.addAttribute("publish", "未发布");
            } else {
                model.addAttribute("publish", "已发布");
            }
            if (null != exam.getStarttime()) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                model.addAttribute("starttime", sdf.format(exam.getStarttime()));
                model.addAttribute("duration", exam.getDuration() + "分钟");
            }
            // 考试人数
            List<Examinee> examineeList = (List<Examinee>) examineeDao.queryByExamId(examId);
            if (!examineeList.isEmpty()) {
                model.addAttribute("renshu", "应到" + examineeList.size() + "人");
                // 组建考生姓名list
                for (Examinee exami : examineeList) {
                    User user = (User) userDao.queryById(exami.getUser_id());
                    String stuName = user.getName();
                    studentNameList.add(stuName);
                }
                model.addAttribute("studentList", studentNameList);
            }
            model.addAttribute("address", exam.getAddress());
        }
        // 根据考试id获取试卷id(一场考试只能配置一份试卷)
        ExamPaper examPaper = (ExamPaper) examPaperDao.queryByExamId(examId);
        Integer paperId = examPaper.getPaper_id();
        // 获取试卷信息
        Paper paper = (Paper) paperDao.queryById(paperId);
        if (null != paper) {
            model.addAttribute("paperName", paper.getTitle());
            // 查询题库
            Depository dep = (Depository) despositoryDao.queryById(paper.getDepository_id());
            // 查询章节
            Content con = (Content) contentDao.queryById(paper.getExtend());
            model.addAttribute("depository", dep.getName() + "->" + con.getTitle());
            ArrayList<QuestionCopy> singleList = new ArrayList<>();
            ArrayList<QuestionCopy> mutiList = new ArrayList<>();
            ArrayList<QuestionCopy> judgeList = new ArrayList<>();
            List<PaperQuestion> paperQuestions = paperQuestionDao.findByPaperId(paper.getId());
            for (PaperQuestion paperQuestion : paperQuestions) {
                QuestionCopy questionCopy = questionCopyDao.findById(paperQuestion.getQuestion_copy_id());
                if(questionCopy.getQuestiontype_id()==1){
                    singleList.add(questionCopy);
                }
                if(questionCopy.getQuestiontype_id()==2){
                    mutiList.add(questionCopy);
                }
                if (questionCopy.getQuestiontype_id()==3){
                    judgeList.add(questionCopy);
                }
            }
            model.addAttribute("singleList",singleList);
            model.addAttribute("mutiList",mutiList);
            model.addAttribute("judgeList",judgeList);
            model.addAttribute("singlecount",singleList.size());
            model.addAttribute("muticount",mutiList.size());
            // 题目数量
            model.addAttribute("questionCount", paperQuestionDao.queryListByPaperId(paper.getId()));
            model.addAttribute("score", paper.getScore());
        }
    }

    /**
     * 启用考试
     */
    public Map<String, Object> openExam(String examId) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        Integer status = 1;
        String msg = "启用成功！";
        ApplicationContext ac = new FileSystemXmlApplicationContext("classpath:spring-context.xml");
        Exam exam = (Exam) ac.getBean("exam");
        exam.setId(Integer.parseInt(examId));
        exam.setStatus("1");
        dao.updateBySelective(exam);
        resultMap.put("status", status);
        resultMap.put("msg", msg);
        return resultMap;
    }
    /**
     * 编辑考试
     *
     * @param model
     * @param examId
     * @param request
     */
    public  Map<String, Object> editExam(Model model, String examId, HttpServletRequest request) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        map.put("exam_id",examId);
        List<Map<String, Object>> studentList = examineeDao.queryExamStudents(map);
        resultMap.put("studentList", studentList);
        resultMap.put("label", "edit");
        // 获取用户信息
        User user = (User) request.getSession().getAttribute("userInfo");
        if (null != user) {
            resultMap.put("userInfo", user);
            // 根据user的unit_id查询unit
            if (null != user.getUnit_id()) {
                Unit unit = (Unit) unitDao.queryById(user.getUnit_id());
                resultMap.put("unit", unit);
            }
            //页面选择查询所有单位
            List<Unit> units = (List<Unit>) unitDao.queryList(null);
            List<JSONObject> jsons = this.getJson(units);
            resultMap.put("units", jsons);
        }
        // 查询考试大类
        resultMap.put("typeList", examParenttypeDao.queryList(null));
        // 查询专业
        resultMap.put("proList", professionDao.queryList(null));
        // 查询级别
        resultMap.put("rankList", rankDao.queryList(null));
        Exam exam = (Exam) dao.queryById(examId);
        /*model.addAttribute("examId", exam.getId());*/
        resultMap.put("examName", exam.getName());
        resultMap.put("typeId", exam.getType_id());
        resultMap.put("proId", exam.getPro_id());
        resultMap.put("examId", examId);
        resultMap.put("rankId", exam.getRank_id());
        Map<String, Object> mapEp = new HashMap<>();
        List<ExamPaper> list = (List<ExamPaper>) examPaperDao.queryList(mapEp);
        if (list.size()>0) {
            resultMap.put("paperId", list.get(0).getPaper_id());
        }
        if (null != exam.getStarttime()) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            resultMap.put("starttime", sdf.format(exam.getStarttime()));
        }
        resultMap.put("duration", exam.getDuration());
        resultMap.put("questionRandom", exam.getQuestionrandom());
        resultMap.put("optionRandom", exam.getOptionrandom());
        resultMap.put("address", exam.getAddress());
        return resultMap;
    }

    public void copyExam(String examId) {
        Exam entity = (Exam) dao.queryById(examId);
        entity.setId(null);
        entity.setPublish(null);
        entity.setStatus(null);
        entity.setStarttime(null);
        dao.add(entity);
    }

    /**
     * 查询所有部门
     * 在查询部门下所有能考试的学生
     */
    public List<User> finUser(Map<String, Object> map) {
        return userDao.findByUnitIdAndRankIdAndProId(map);
    }
    public  List<JSONObject> getJson(List<Unit> units) {
        List<JSONObject> jsons = new ArrayList<JSONObject>();
        for (Unit unit1 : units) {
            JSONObject json = new JSONObject();
            json.put("name", unit1.getName());
            json.put("id", unit1.getId());
            jsons.add(json);
        }
        return jsons;
    }

    public Map<String, Object> findUserByExamId(String userid, String examId) {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> map = new HashMap<>();
        map.put("exam_id",examId);
        List<Examinee> ts = (List<Examinee>) examineeDao.queryList(map);
        for (Examinee t : ts) {
            User us = (User) userDao.queryById(t.getUser_id());
            t.setExtend(us.getName());
        }
        Object obj = null;
        if (StringUtils.isBlank(userid)) {
            obj = ts.get(0).getUser_id();
        } else {
            obj = userid;
        }
        User user = (User) userDao.queryById(obj);
        Profession profession = (Profession) professionDao.queryById(user.getPro_id());
        Rank rank = (Rank) rankDao.queryById(user.getRank_id());
        //查找人员的考试时间
        Exam exam = (Exam) examDao.queryById(examId);
        resultMap.put("rank",rank);
        resultMap.put("profession",profession);
        resultMap.put("exam",exam);
        resultMap.put("list",ts);
        resultMap.put("examinee",user);
        return resultMap;
    }

    public Map<String, Object> questionsView(String paperId, String path) {
        Map<String,Object> resultMap = new HashMap<>();
        ArrayList<Question> singleList = new ArrayList<>();
        ArrayList<Question> mutiList = new ArrayList<>();
        ArrayList<Question> judgeList = new ArrayList<>();
        List<PaperQuestion> paperQuestions = paperQuestionDao.findByPaperId(paperId);
        for (PaperQuestion paperQuestion : paperQuestions) {
            Question question = (Question) questionDao.queryById(paperQuestion.getQuestion_id());
            question.setPicture(path+question.getPicture());
            question.setApic(path+question.getApic());
            question.setBpic(path+question.getBpic());
            question.setCpic(path+question.getCpic());
            question.setDpic(path+question.getDpic());
            if(question.getQuestiontype_id()==1){
                singleList.add(question);
            }
            if(question.getQuestiontype_id()==2){
                mutiList.add(question);
            }
            if (question.getQuestiontype_id()==3){
                judgeList.add(question);
            }
        }
        resultMap.put("singleList",singleList);
        resultMap.put("mutiList",mutiList);
        resultMap.put("judgeList",judgeList);
        return resultMap;
    }
}
